package com.xiaolei.library.Utils;

/**
 * 字节转16进制工具类
 */
public class ByteHexUtil
{
    private static String[] strHex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};

    /**
     * 将单个字节，转换成16进制字符串
     *
     * @param bt
     * @return
     */
    public static String byteTo16(byte bt)
    {
        int low = (bt & 15);
        int high = bt >> 4 & 15;
        return "0x" + strHex[high] + "" + strHex[low];
    }

    /**
     * 将字节数组，转换成16进制字节字符串
     *
     * @param array
     * @return
     */
    public static String byteArrayToHex(byte[] array)
    {
        StringBuilder builder = new StringBuilder();
        builder.append("[");
        for (int i = 0; i < array.length; i++)
        {
            byte bt = array[i];
            int low = (bt & 15);
            int high = bt >> 4 & 15;
            builder.append("0x").append(strHex[high]).append(strHex[low]).append(",");
        }
        if (array.length > 0)
        {
            builder.replace(builder.length() - 1, builder.length(), "");
        }
        builder.append("]");
        return builder.toString();
    }
}
